<script setup lang="ts">
import type { CodeLoginInformationProps } from '@croco/framework/libraries';

import { $t } from '@croco/framework/locales';

defineOptions({ name: 'CodeLoginForm' });

defineProps<{
    rules: {};
}>();

const emit = defineEmits<{ send: [CodeLoginInformationProps] }>();

const codeLoginFormRef = ref();
const form = defineModel<CodeLoginInformationProps>({
    default: {
        mobile: undefined,
        code: undefined,
    },
});
const disabled = ref(false);
const time = ref(0);

const handleSend = async () => {
    codeLoginFormRef.value
        .validateField('mobile')
        .then((validate: boolean) => {
            if (validate) {
                emit('send', form.value);
                disabled.value = true;
                time.value = 60;
                const timer = setInterval(() => {
                    time.value -= 1;
                    if (time.value < 1) {
                        clearInterval(timer);
                        disabled.value = false;
                        time.value = 0;
                    }
                }, 1000);
            }
        })
        .catch(() => {});
};

defineExpose({
    validate: (validate: (status: boolean) => void) => codeLoginFormRef.value.validate(validate),
});
</script>

<template>
    <el-form ref="codeLoginFormRef" :model="form" :rules="rules" style="height: 100px">
        <el-form-item prop="mobile">
            <el-input v-model="form.mobile" size="large" :placeholder="$t('authentication.mobile')" clearable />
        </el-form-item>
        <el-form-item prop="code">
            <el-row :gutter="5" style="width: 100%; margin-left: 0; margin-right: 0">
                <el-col :span="18">
                    <el-input v-model="form.code" size="large" :placeholder="$t('authentication.code')" />
                </el-col>
                <el-col :span="6" style="padding-right: 0">
                    <el-button style="width: 100%" size="large" :disabled="disabled" @click="handleSend">
                        <span v-if="disabled"> {{ $t('authentication.sendText', [time]) }}</span>
                        <span v-else> {{ $t('authentication.sendCode') }}</span>
                    </el-button>
                </el-col>
            </el-row>
        </el-form-item>
    </el-form>
</template>

<style scoped></style>
